package main

import (
	"embed"
	"github.com/cloudwego/hertz/pkg/app/server"
	"github.com/cloudwego/hertz/pkg/common/hlog"
	"github.com/cloudwego/hertz/pkg/common/tracer/stats"
	"github.com/hertz-contrib/swagger"
	"path/filepath"
	"runtime"
	"wails-hertz/docs"
	"wails-hertz/server/configuration/log"
	"wails-hertz/server/configuration/middlewares"
	"wails-hertz/server/configuration/sw"
	"wails-hertz/server/kits/files"
	"wails-hertz/server/web"

	"github.com/wailsapp/wails/v2"
	"github.com/wailsapp/wails/v2/pkg/options"
	"github.com/wailsapp/wails/v2/pkg/options/assetserver"

	swaggerFiles "github.com/swaggo/files"
)

//go:embed all:frontend/dist
var assets embed.FS

var AppTitle string = "Wails-Hertz"

// @host localhost:8877
// @BasePath /
// @schemes http
func main() {
	// 启动 Hertz HTTP 服务（在 goroutine 中运行，不阻塞 Wails）
	go func() {
		startHertz()
	}()

	// Create an instance of the app structure
	app := NewApp()
	// Create application with options
	err := wails.Run(&options.App{
		Title:  AppTitle,
		Width:  1024,
		Height: 768,
		AssetServer: &assetserver.Options{
			Assets: assets,
		},
		BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1},
		OnStartup:        app.startup,
		Bind: []interface{}{
			app,
		},
	})

	if err != nil {
		println("Error:", err.Error())
	}
}

func startHertz() {
	// 指定工作目录
	workdir := workspace()

	// 日志信息处理
	logDir := filepath.Join(workdir, "logs")
	logName := "wails.log"
	log.InitLog(logDir, logName)
	hlog.SetLogger(log.GetHertzLogger())
	hlog.Info("服务启动中...")

	// 链路追踪
	_, _, err := sw.InitTracer(AppTitle)
	if err != nil {
		hlog.Info("链路追踪初始化异常..." + err.Error())
		return
	}

	// h := server.Default()
	h := server.Default(
		server.WithHostPorts("127.0.0.1:8877"),
		server.WithTraceLevel(stats.LevelBase), // 关键配置
	)
	// 注册全局中间件（按注册顺序执行）
	h.Use(middlewares.TracerMiddleware())

	// 注册路由
	web.RegisterRoutes(h)

	// swagger 工具
	docs.SwaggerInfo.BasePath = "/"
	h.GET("/swagger/*any", swagger.WrapHandler(swaggerFiles.Handler))

	// 监听请求
	h.Spin()
}

// MACOS: /Users/liuwei/Library/Containers/wails-hertz
// Windows:  默认 exe 所在目录为工作目录
func workspace() string {
	exeDir := files.GetExeDirIgnoreError()
	appDir := files.GetMacAppDir(AppTitle)

	// 指定当前的工作目录
	userDir := appDir
	if runtime.GOOS == "windows" {
		userDir = exeDir // windows 默认 exe 所在目录为工作目录
	}
	mkdirErr := files.MkDirsWithParents(userDir)
	if mkdirErr != nil {
		println("Error:", mkdirErr.Error())
		return userDir
	}
	return userDir
}
